----------------------------------------------------------------
-- TomeWindow - Live Event Implementation
--
--  This file contains all of the initialization and callack
--  functions for the Live Event section of the Tome of Knowledge.
-- 
----------------------------------------------------------------


-- Constants
local PARENT_WINDOW = "LiveEventPageWindowContentsChild"
local NUM_REWARDS = 3

local COLOR_ACTIVE_TASK     = { r= 95, g= 57, b= 36 }
local COLOR_INACTIVE_TASK   = { r=153, g=111, b= 88 }

-- Variables
TomeWindow.LiveEventRewards = {}
TomeWindow.LiveEventAlerts = {}
TomeWindow.CurrentLiveEventId = 0
TomeWindow.CurrentLiveEventName = L""
local taskWindowCount = 0
local taskTextWindowCount = 0

TomeWindow.RealmResourceQuestWindowID = 0

----------------------------------------------------------------
-- Local Functions

local function NewLiveEventAlert( paramName, paramText )
    return { section = GameData.Tome.SECTION_LIVE_EVENT, entry = 0, subEntry = 0, name = paramName, text = paramText, xp = 0, useName = true }
end

local function SetLiveEventActive( isActive )
    WindowSetShowing( "TomeWindowLiveEventBookmark", isActive )
    
    if ( not isActive and TomeWindow.GetCurrentState() == TomeWindow.PAGE_LIVE_EVENT )
    then
        TomeWindow.SetState( TomeWindow.PAGE_TITLE_PAGE, {} )
    end
end

local function GetSavedAlertsTable()
    if( TomeWindow.LiveEventAlerts.events == nil )
    then
        TomeWindow.LiveEventAlerts.events = {}
    end

    local uniqueKey = tostring(SystemData.Server.Name..GameData.Player.name..TomeWindow.CurrentLiveEventId)

    if( TomeWindow.LiveEventAlerts.events[uniqueKey] == nil )
    then
        TomeWindow.LiveEventAlerts.events[uniqueKey] = {}
    end

    if( TomeWindow.LiveEventAlerts.events[uniqueKey].tasks == nil )
    then
        TomeWindow.LiveEventAlerts.events[uniqueKey].tasks = {}
    end

    if( TomeWindow.LiveEventAlerts.events[uniqueKey].tasksDone == nil )
    then
        TomeWindow.LiveEventAlerts.events[uniqueKey].tasksDone = {}
    end
    
    return TomeWindow.LiveEventAlerts.events[uniqueKey]
end



----------------------------------------------------------------
-- Live Event Functions
----------------------------------------------------------------

function TomeWindow.InitializeLiveEvent()

    TomeWindow.Pages[ TomeWindow.PAGE_LIVE_EVENT ]
        = TomeWindow.NewPageData( TomeWindow.Sections.SECTION_LIVE_EVENT,
                    "LiveEvent",
                    TomeWindow.OnShowLiveEvent,
                    TomeWindow.OnLiveEventUpdateNavButtons,
                    TomeWindow.OnLiveEventPreviousPage,
                    TomeWindow.OnLiveEventNextPage,
                    TomeWindow.OnLiveEventMouseOverPreviousPage,
                    TomeWindow.OnLiveEventMouseOverNextPage,
                    TomeWindow.OnShowLiveEvent ) -- REALLY do call this every time it's shown!
                    
    WindowRegisterEventHandler( "TomeWindow", SystemData.Events.TOME_LIVE_EVENT_UPDATED, "TomeWindow.OnUpdateLiveEvent" )
    WindowRegisterEventHandler( "TomeWindow", SystemData.Events.TOME_LIVE_EVENT_TASKS_UPDATED, "TomeWindow.OnUpdateLiveEventTasks" )
    WindowRegisterEventHandler( "TomeWindow", SystemData.Events.RRQ_LIST_UPDATED, "TomeWindow.OnUpdateLiveEventTasks" )
    WindowRegisterEventHandler( "TomeWindow", SystemData.Events.TOME_LIVE_EVENT_PLAYER_CONTRIBUTION_UPDATED, "TomeWindow.OnUpdatePlayerContribution" )

    LabelSetText( PARENT_WINDOW.."ProgressLevel1Label", GetString( StringTables.Default.LABEL_BASIC_REWARDS ) )
    LabelSetText( PARENT_WINDOW.."ProgressLevel2Label", GetString( StringTables.Default.LABEL_ADVANCED_REWARDS ) )
    LabelSetText( PARENT_WINDOW.."ProgressLevel3Label", GetString( StringTables.Default.LABEL_ELITE_REWARDS ) )
    
    for level = 1, NUM_REWARDS
    do
        ButtonSetDisabledFlag( PARENT_WINDOW.."ProgressBarCheck"..level, true )
        ButtonSetDisabledFlag( PARENT_WINDOW.."ProgressReward"..level, true )
    end
    

    PageWindowAddPageBreak( "LiveEventPageWindow", PARENT_WINDOW.."LoreText" )
        

    TomeWindow.OnUpdateLiveEvent()
end

function TomeWindow.OnShowLiveEvent( entry )
    SetLiveEventActive( IsLiveEventActive() )
    
    -- Request an update on the realm resource quest status
    -- but only if we have one, just opened the live event page, and the data is stale
    if ( IsLiveEventActive() and WindowGetShowing( PARENT_WINDOW.."RRQ" ) == true )
    then
        -- the below call will actually just do a one-time ping for an update
        -- with GameDefs.MapLevel.PAIRING_MAP, we don't have to worry about calling MapEndAutoUpdating
        -- and the very likely problem of having a case where that somehow did not get called. 
        MapBeginAutoUpdating( GameDefs.MapLevel.PAIRING_MAP, GameData.Player.zone, SystemData.AutoUpdateType.RRQS ) 
    end
end

function TomeWindow.OnUpdateLiveEvent()

    local eventData = GetLiveEventData()
    if( eventData == nil )
    then
        SetLiveEventActive( false )
        return
    end
    
    SetLiveEventActive( true )
    
    TomeWindow.CurrentLiveEventId = eventData.eventId
    TomeWindow.CurrentLiveEventName = eventData.title

    LabelSetText( PARENT_WINDOW.."Title", wstring.upper( eventData.title ) )
    LabelSetText( PARENT_WINDOW.."SubTitle", eventData.subTitle )
    LabelSetText( PARENT_WINDOW.."SummaryText", eventData.description )
    LabelSetText( PARENT_WINDOW.."LoreText", eventData.loreText )
        
    TomeWindow.SetPageHeaderText( TomeWindow.PAGE_LIVE_EVENT,
                                  GetStringFromTable( "LiveEventStrings", StringTables.LiveEventStrings.LABEL_LIVE_EVENT ),
                                  eventData.title )

    -- Check to see if the user has already been notified about this live event
    local savedAlerts = GetSavedAlertsTable()
    if( savedAlerts.overall ~= true )
    then
        local alert = NewLiveEventAlert( TomeWindow.CurrentLiveEventName,
                                         GetStringFromTable( "LiveEventStrings", StringTables.LiveEventStrings.LABEL_LIVE_EVENT_ALERT ) )

        TomeAlertWindow.QueueAlert( alert )
        savedAlerts.overall = true
    end

    TomeWindow.OnUpdateLiveEventTasks()

end

function TomeWindow.OnUpdateLiveEventTasks()

    local tasks = GetLiveEventTasks()
    if( tasks == nil )
    then
        return
    end
    
    -- Update overall progress
    local lastLevelThreshold = 0
    local statusBarPercent = 0
    
    if tasks.rewards ~= nil
    then
        for level = 1, NUM_REWARDS do
            local levelPercent = 0
            if( tasks.rewards[level].threshold - lastLevelThreshold > 0 )
            then
                levelPercent = ( tasks.overallCurrentValue - lastLevelThreshold ) / ( tasks.rewards[level].threshold - lastLevelThreshold )
            end
            if( levelPercent > 1.0 )
            then
                statusBarPercent = statusBarPercent + ( 1.0 / NUM_REWARDS )
            elseif( levelPercent > 0 )
            then
                statusBarPercent = statusBarPercent + ( 1.0 / NUM_REWARDS ) * levelPercent
            end
            lastLevelThreshold = tasks.rewards[level].threshold

            local checked = tasks.overallCurrentValue >= tasks.rewards[level].threshold
            ButtonSetPressedFlag( PARENT_WINDOW.."ProgressBarCheck"..level, checked )
            ButtonSetStayDownFlag( PARENT_WINDOW.."ProgressBarCheck"..level, true )
            ButtonSetDisabledFlag( PARENT_WINDOW.."ProgressBarCheck"..level, true )

            if( tasks.rewards[level].item ~= nil )
            then
                local texture, x, y = GetIconData( tasks.rewards[level].item.iconNum )
                DynamicImageSetTexture( PARENT_WINDOW.."ProgressReward"..level.."IconBase", texture, x, y )
            end
            WindowSetShowing( PARENT_WINDOW.."ProgressReward"..level, tasks.rewards[level].item ~= nil )
        end
    end
    StatusBarSetMaximumValue( PARENT_WINDOW.."ProgressBarStatus", 1.0 )
    StatusBarSetCurrentValue( PARENT_WINDOW.."ProgressBarStatus", statusBarPercent )
    WindowSetShowing( PARENT_WINDOW.."Progress", tasks.rewards ~= nil )
    
    local contributionActive = tasks.playerContributionActive
    if( contributionActive )
    then
        LabelSetText( PARENT_WINDOW.."PlayerContributionLabel",
                      GetStringFormat( StringTables.Default.LABEL_PLAYER_CONTRIBUTION_FORMAT, { tasks.playerContribution } ) )
    end
    
    WindowSetShowing( PARENT_WINDOW.."PlayerContributionLabel", contributionActive )
    
    -- Realm Resource Race
    if tasks.rewards == nil and RRQProgressBar ~= nil
    then
        local rrqData = RRQProgressBar.GetFirstQuestDataOfType(GameData.RRQDisplayType.ERRQDISPLAY_LIVE_EVENT)
        
        if rrqData ~= nil
        then
            
            for iRealm=GameData.Realm.ORDER, GameData.Realm.DESTRUCTION --[1, 2]
            do
                LabelSetText( PARENT_WINDOW.."RRQ".."RealmName"..iRealm, GetRealmName( iRealm ) )
                
                if rrqData.realmProgress[iRealm] ~= nil 
                then
                    local curPointsText = L""..rrqData.realmProgress[iRealm].curVal
                    if (rrqData.realmProgress[iRealm].maxVal == 100)
                    then
                        curPointsText = curPointsText..L"%"
                    end
                    
                    LabelSetText( PARENT_WINDOW.."RRQ".."RealmPoints"..iRealm, curPointsText )
                end
            end --end for each realm
            
            if not DoesWindowExist(PARENT_WINDOW.."RRQ".."Status")
            then
                --DEBUG(L"TomeWindow setting up RRQ Status")
                
                -- setup Realm Resource Quest Status Window
                TomeWindow.RealmResourceQuestWindowID = RRQProgressBar.Create( PARENT_WINDOW.."RRQ".."Status", 
                                                                                    PARENT_WINDOW.."RRQ".."BarContainer",
                                                                                    GameData.RRQDisplayType.ERRQDISPLAY_LIVE_EVENT)
            end
            
            if not (RRQProgressBar.GetRRQuestIDfromWindowID( TomeWindow.RealmResourceQuestWindowID ) == rrqData.rrquestID)
            then
                RRQProgressBar.SetRRQuestID( TomeWindow.RealmResourceQuestWindowID, rrqData.rrquestID )
            end
            
            WindowSetShowing( PARENT_WINDOW.."RRQ", true )
        end -- end if rrqData ~= nil 
    else
        WindowSetShowing( PARENT_WINDOW.."RRQ", false )
    end -- end if tasks.rewards == nil
    
    TomeWindow.LiveEventRewards = tasks.rewards
    
    local taskWindowName = PARENT_WINDOW.."Task"
    local taskTextWindowName = PARENT_WINDOW.."Text"
    local anchorWindow = PARENT_WINDOW.."LoreText"
    local taskCount = 0
    local taskAlertAdded = false
    local taskDoneAlertAdded = false
    local taskWidth, taskMinHeight = 400, 23
    local taskTextCount = 0
    
    -- returns the new window created count
    local function CreateTaskWindowOnDemand( winName, templateName, numWindowsCreated )
        if( not DoesWindowExist( winName ) )
        then
            -- Need to create a new window
            numWindowsCreated = numWindowsCreated + 1
            
            CreateWindowFromTemplate( winName, templateName, PARENT_WINDOW )
        end
        
        -- add the anchor using the upvalue local anchor window
        WindowClearAnchors( winName )
        WindowAddAnchor( winName, "bottom", anchorWindow, "top", 0, 15 )
    
        -- Set the new anchor window
        anchorWindow = winName
        
        return numWindowsCreated
    end

    for index, task in ipairs( tasks )
    do
        local curWinName = L""
        
        if( not task.isOnlyText )
        then
            taskCount = taskCount + 1
            
            curWinName = taskWindowName..taskCount
            
            taskWindowCount = CreateTaskWindowOnDemand( curWinName, "LiveEventTaskEntryDef", taskWindowCount )
            
            ButtonSetStayDownFlag( curWinName.."CompletedBtn", true )
            ButtonSetDisabledFlag( curWinName.."CompletedBtn", true )
        else
            taskTextCount = taskTextCount +1
            
            curWinName = taskTextWindowName..taskTextCount
            
            taskTextWindowCount = CreateTaskWindowOnDemand( curWinName, "LiveEventTaskTextEntryDef", taskTextWindowCount )
        end
        
        

        local taskText = task.name
        
        if( task.hidden and not task.isOnlyText )
        then
            ButtonSetPressedFlag( curWinName.."CompletedBtn", false )
        elseif( not task.isOnlyText )
        then
            ButtonSetPressedFlag( curWinName.."CompletedBtn", task.currentValue == task.maxValue )
            taskText = GetFormatStringFromTable( "LiveEventStrings",
                                                 StringTables.LiveEventStrings.LABEL_LIVE_EVENT_TASK_FORMAT,
                                                 { task.name, task.currentValue, task.maxValue } )
        end
        
        if( task.active )
        then
            LabelSetTextColor( curWinName.."Text", COLOR_ACTIVE_TASK.r, COLOR_ACTIVE_TASK.g, COLOR_ACTIVE_TASK.b )
        else
            LabelSetTextColor( curWinName.."Text", COLOR_INACTIVE_TASK.r, COLOR_INACTIVE_TASK.g, COLOR_INACTIVE_TASK.b )
        end
        
        LabelSetText( curWinName.."Text", taskText )
        WindowSetId( curWinName, task.taskId )

        local _, labelHeight = WindowGetDimensions( curWinName.."Text" )
        WindowSetDimensions( curWinName, taskWidth, math.max( taskMinHeight, labelHeight ) )
        
        if( task.isOnlyText )
        then
            continue
        end
        
        -- Check to see if the user has already been notified about this task
        local savedAlerts = GetSavedAlertsTable()
        if( task.active and taskAlertAdded == false and
            savedAlerts.tasks[task.taskId] ~= true )
        then
            local alert = NewLiveEventAlert( TomeWindow.CurrentLiveEventName,
                                             GetStringFromTable( "LiveEventStrings", StringTables.LiveEventStrings.LABEL_LIVE_EVENT_ALERT ) )

            TomeAlertWindow.QueueAlert( alert )
            savedAlerts.tasks[task.taskId] = true
            taskAlertAdded = true -- Only pop one alert for the update, in case we're mid way through the event and settings have been cleared
        end
        
        -- Check to see if the user has completed the current task, and been notified about it
        if( task.maxValue ~= 0 and task.currentValue >= task.maxValue and taskDoneAlertAdded == false and
            savedAlerts.tasksDone[task.taskId] ~= true )
        then
            local alert = NewLiveEventAlert( TomeWindow.CurrentLiveEventName,
                                             GetStringFromTable( "LiveEventStrings", StringTables.LiveEventStrings.LABEL_LIVE_EVENT_TASK_COMPLETE ) )

            TomeAlertWindow.QueueAlert( alert )
            savedAlerts.tasksDone[task.taskId] = true
            taskDoneAlertAdded = true -- One per update
        end
    end
    
    -- show the right number of buttons
    for index = 1, taskWindowCount
    do
        local show = index <= taskCount
        local windowName = taskWindowName..index
        if( WindowGetShowing( windowName ) ~= show ) then
            WindowSetShowing( windowName, show )
        end
        if( show == false ) then
           WindowSetId( windowName, 0 )
        end
    end
    
    -- show the right number of labels
    for index = 1, taskTextWindowCount
    do
        local show = index <= taskTextCount
        local windowName = taskTextWindowName..index
        if( WindowGetShowing( windowName ) ~= show ) then
            WindowSetShowing( windowName, show )
        end
        if( show == false ) then
           WindowSetId( windowName, 0 )
        end
    end

    PageWindowUpdatePages( "LiveEventPageWindow" )
end

function TomeWindow.OnUpdatePlayerContribution()
    local contributionValue = GetLiveEventPlayerContribution()
    if( contributionValue )
    then
        LabelSetText( PARENT_WINDOW.."PlayerContributionLabel", GetStringFormat( StringTables.Default.LABEL_PLAYER_CONTRIBUTION_FORMAT, {contributionValue} ) )
    end
    WindowSetShowing( PARENT_WINDOW.."PlayerContributionLabel", contributionValue ~= nil )
end

function TomeWindow.OnMouseOverLiveEventReward()
    local rewardId = WindowGetId( SystemData.ActiveWindow.name )
    
    
    if( TomeWindow.LiveEventRewards[rewardId] ~= nil )
    then
        local itemData = TomeWindow.LiveEventRewards[rewardId].item
        if( itemData ~= nil and itemData.id ~= nil )
        then
            Tooltips.CreateItemTooltip( itemData, SystemData.ActiveWindow.name, Tooltips.ANCHOR_WINDOW_RIGHT )
        end
    end
end

---------------------------------------------------------
-- > Nav Buttons

function TomeWindow.OnLiveEventUpdateNavButtons()
    if ( TomeWindow.GetCurrentState() ~= TomeWindow.PAGE_LIVE_EVENT ) then
        return
    end
    
    local curPage   = PageWindowGetCurrentPage( "LiveEventPageWindow" )
    local numPages  = PageWindowGetNumPages( "LiveEventPageWindow" )
    WindowSetShowing( "TomeWindowPreviousPageButton", curPage > 1 )
    WindowSetShowing( "TomeWindowNextPageButton", curPage + 2 <= numPages )
end

function TomeWindow.OnLiveEventPreviousPage()
    TomeWindow.FlipPageWindowBackward( "LiveEventPageWindow")
end

function TomeWindow.OnLiveEventNextPage()
    TomeWindow.FlipPageWindowForward( "LiveEventPageWindow")
end

function TomeWindow.OnLiveEventMouseOverPreviousPage()
    local lines = {}    
    local curPage   = PageWindowGetCurrentPage( "LiveEventPageWindow" )
    local numPages  = PageWindowGetNumPages( "LiveEventPageWindow" )
    if( curPage > 1 ) then
        -- Previous Pages
        lines[1] = GetStringFromTable( "LiveEventStrings", StringTables.LiveEventStrings.LABEL_LIVE_EVENT )
        lines[2] = GetString( StringTables.Default.TEXT_CONTINUED )
    end 
    TomeWindow.CreateBackButtonTooltip( lines )
end

function TomeWindow.OnLiveEventMouseOverNextPage()
    local lines = {}    
    local curPage   = PageWindowGetCurrentPage( "LiveEventPageWindow" )
    local numPages  = PageWindowGetNumPages( "LiveEventPageWindow" )
    if( curPage + 2 <= numPages ) then
        -- Next Pages
        lines[1] = GetStringFromTable( "LiveEventStrings", StringTables.LiveEventStrings.LABEL_LIVE_EVENT )
        lines[2] = GetString( StringTables.Default.TEXT_CONTINUED )
    end 
    TomeWindow.CreateNextButtonTooltip( lines )
end